package com.software.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @BelongsProject: Second-hand-trading-platform
 * @BelongsPackage: com.software.controller
 * @Author: wyj
 * @CreateTime: 2024-02-27  13:57
 * @Description:
 * @Version: 1.0
 */
@RestController
public class CaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        response.setDateHeader("Expires", 0); // 设置响应头立即 过期
        //指示浏览器和代理服务器不要缓存这个响应。
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        //设置多个Cache-Control头，指示浏览器和代理服务器不要缓存这个响应。
        response.addHeader("Cache-Control", "post-check=0 ,pre-check=0");
        //- 设置Pragma头作为HTTP 1.0向后兼容的指令，告诉缓存不要缓存这个响应。
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        // begin
        String text = defaultKaptcha.createText();

        request.getSession().setAttribute("captcha", text);
        System.out.println("验证码内容" + text);
        System.out.println("test验证码内容" + request.getSession().getAttribute("captcha"));
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //end
        }

    }

}
